# -*- coding: utf-8 -*-
# @Time    : 2021/10/26 16:53
# @Author  : huangwei
# @File    : method.py
# @Software: PyCharm
import copy
import math
import imutils
import numpy as np
import cv2
from skimage import measure
import os

from draw_method import sort_box, draw_img

# 创建文件夹
from excel_method import get_rotate_crop_image


def create_dir( dir_path ):
    """创建文件夹"""
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    else:
        print("%s is exists" % dir_path)


def fill_rect_table( row_lines, col_lines ):
    """补齐为矩形"""
    # 找出 x_min, x_max, y_min, y_max
    line_array = np.array(row_lines + col_lines)
    x_min = min(line_array[:, 0]) + 1
    y_min = min(line_array[:, 1]) + 1
    x_max = max(line_array[:, 2]) - 1
    y_max = max(line_array[:, 3]) - 1

    up_line = [x_min, y_min, x_max, y_min]
    down_line = [x_min, y_max, x_max, y_max]
    left_line = [x_min, y_min, x_min, y_max]
    right_line = [x_max, y_min, x_max, y_max]

    row_lines.append(up_line)
    row_lines.append(down_line)
    col_lines.append(left_line)
    col_lines.append(right_line)

    row_lines = sort_line(row_lines)
    col_lines = sort_line(col_lines, axis=1)

    return row_lines, col_lines


def resize( img, size ):
    """
    将图片转成符合模型输入的形状
    :param img:
    :param size:
    :return:
    """
    img_h, img_w = img.shape[:2]
    w, h = size

    ratio = min(w / img_w, h / img_h)
    new_w = int(img_w * ratio)
    new_h = int(img_h * ratio)

    resize_img = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_CUBIC)

    kernel_sharpen = np.array([
        [0, -1, 0],
        [-1, 5, -1],
        [0, -1, 0]])
    resize_img = cv2.filter2D(resize_img, -1, kernel_sharpen)

    # cv2.imwrite('temp_path/resize_img.png', resize_img)

    fill_value = [128, 128, 128]
    boxed_image = np.zeros((h, w, 3), dtype=np.uint8)
    boxed_image[:] = fill_value
    boxed_image[:new_h, :new_w, :] = resize_img
    # cv2.imwrite('temp_path/box_img.png', boxed_image)

    # 分别为长、宽变化的比例
    fx = new_w / img_w
    fy = new_h / img_h

    return boxed_image, fx, fy


def get_line( coords ):
    """
    返回该点集的最小外接矩形的与较长边平行的中心线
    :param coords:
    :return:
    """
    rect = cv2.minAreaRect(coords[:, ::-1])
    box = cv2.boxPoints(rect)
    box = box.reshape((8,)).tolist()

    # 将外接矩形四个点进行排序确定每一个点的位置
    box = sort_box(box)
    x1, y1, x2, y2, x3, y3, x4, y4 = box

    w = (np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) + np.sqrt((x3 - x4) ** 2 + (y3 - y4) ** 2)) / 2
    h = (np.sqrt((x2 - x3) ** 2 + (y2 - y3) ** 2) + np.sqrt((x1 - x4) ** 2 + (y1 - y4) ** 2)) / 2

    if w < h:
        xmin = (x1 + x2) / 2
        xmax = (x3 + x4) / 2
        ymin = (y1 + y2) / 2
        ymax = (y3 + y4) / 2

    else:
        xmin = (x1 + x4) / 2
        xmax = (x2 + x3) / 2
        ymin = (y1 + y4) / 2
        ymax = (y2 + y3) / 2

    return [xmin, ymin, xmax, ymax]


def get_table_line( pred_line, axis, alph ):
    """
    根据模型得出的结果提取出识别出的横线和竖线
    :param pred_line:
    :param axis:
    :param alph:
    :return:
    """
    # axis=0 横线
    # axis=1 竖线
    lables = measure.label(pred_line > 0, connectivity=2)
    regions = measure.regionprops(lables)

    if axis == 1:
        lines = [get_line(line.coords) for line in regions if line.bbox[2] - line.bbox[0] > alph]
    else:
        lines = [get_line(line.coords) for line in regions if line.bbox[3] - line.bbox[1] > alph]

    return lines


def not_par_line( lines, alph=1 ):
    """
    去除不平行的线
    :param lines:
    :param alph:
    :return:
    """
    degree_list = []
    line_num = len(lines)
    for line in lines:
        x1, y1, x2, y2 = line
        if x1 != x2:
            k12 = (y2 - y1) / (x2 - x1)
            a12 = math.degrees(math.atan(k12))
        else:
            a12 = 90
        degree_list.append(a12)

    sort_list = sorted(degree_list)
    mid_degree = sort_list[line_num // 2]

    new_lines = []
    for i in range(line_num):
        if abs(degree_list[i] - mid_degree) < alph:
            new_lines.append(lines[i])

    return new_lines


def sort_line( lines, axis=0 ):
    """
    对线进行从左到右从上到下排序
    :param lines:
    :param axis:
    :return:
    """
    center_list = []
    for line in lines:
        x1, y1, x2, y2 = line
        c_x, c_y = (x1 + x2) / 2, (y1 + y2) / 2

        if axis == 0:
            center_list.append(c_y)
        else:
            center_list.append(c_x)

    sort_list = np.argsort(center_list)

    new_lines = []
    for index in sort_list:
        new_lines.append(lines[index])

    return new_lines


def dist( p1, p2 ):
    """ 两个点之间的距离 """
    return np.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)


def find_unclear_lines( lines, alph=15 ):
    """
    将断续的横线或竖线进行连接
    :param lines:
    :param alph:
    :return:
    """
    # 找出不清楚的线并且合并线段
    line_num = len(lines)

    new_lines = []
    line_used = []

    # 四个点在一条直线上且最近的两个点距离小于 alph
    for i in range(line_num - 1):
        if i not in line_used:
            x1, y1, x2, y2 = lines[i]
            if x1 != x2:
                k12 = (y2 - y1) / (x2 - x1)
                a12 = math.degrees(math.atan(k12))
            else:
                a12 = 90

            for j in range(i + 1, line_num):
                if j not in line_used:
                    x1, y1, x2, y2 = lines[i]
                    x3, y3, x4, y4 = lines[j]

                    # 计算a34
                    if x3 != x4:
                        k34 = (y4 - y3) / (x4 - x3)
                        a34 = math.degrees(math.atan(k34))
                    else:
                        a34 = 90

                    # 计算 a13
                    if x1 != x3:
                        k13 = (y3 - y1) / (x3 - x1)
                        a13 = math.degrees(math.atan(k13))
                    else:
                        a13 = 90

                    # 计算 a14
                    if x1 != x4:
                        k14 = (y4 - y1) / (x4 - x1)
                        a14 = math.degrees(math.atan(k14))
                    else:
                        a14 = 90

                    # 如果 a12 和 a13相差不超过1°则认为 12和13重合
                    # 左右和右左
                    # 12与13
                    # 34与31
                    # 求四个点之间的距离，最短距离小于alph则连接，用最长的那条取代
                    if abs(a13 - a12) < 1 or abs(a34 - a13) < 1:
                        dis13 = dist((x1, y1), (x3, y3))
                        dis14 = dist((x1, y1), (x4, y4))
                        dis23 = dist((x2, y2), (x3, y3))
                        dis24 = dist((x2, y2), (x4, y4))
                        dist_list = [dis13, dis14, dis23, dis24]
                        min_dis = min(dist_list)
                        # print("min dis is:", min_dis)

                        if min_dis < alph:
                            max_index = dist_list.index(max(dist_list))
                            # print("max index:", max_index)
                            if max_index == 0:
                                # 返回13或31
                                if x1 > x3 or y1 > y3:
                                    lines[i] = [x3, y3, x1, y1]
                                else:
                                    lines[i] = [x1, y1, x3, y3]
                            elif max_index == 1:
                                # 返回14
                                if x1 > x4 or y1 > y4:
                                    lines[i] = [x4, y4, x1, y1]
                                else:
                                    lines[i] = [x1, y1, x4, y4]
                            elif max_index == 2:
                                # 返回23
                                if x2 > x3 or y2 > y3:
                                    lines[i] = [x3, y3, x2, y2]
                                else:
                                    lines[i] = [x2, y2, x3, y3]
                            else:
                                # 返回24
                                if x2 > x4 or y2 > y4:
                                    lines[i] = [x4, y4, x2, y2]
                                else:
                                    lines[i] = [x2, y2, x4, y4]

                            new_lines.append(lines[i])

                            # 记录已经使用的线段
                            # print("use:", (i, j))
                            line_used.append(i)
                            line_used.append(j)

    for i in range(line_num):
        if i not in line_used:
            new_lines.append(lines[i])

    return new_lines


def get_text_boxes( img, text_detector, text_recognizer, row_lines ):
    """
    图片放大为2*2，分割成4*1，沿横线进行切割后分别识别每个子图中的文字框
    :param text_recognizer:
    :param text_detector:
    :param img:
    :param row_lines:
    :return:
    """

    if len(row_lines) < 20:
        ori_img = img.copy()
        all_dt_boxes = text_detector(ori_img)

        if all_dt_boxes is None:
            return None, None

        # 将识别出的框裁剪出来,再进行文字识别
        img_crop_list = []
        for bno in range(len(all_dt_boxes)):
            tmp_box = copy.deepcopy(all_dt_boxes[bno])
            img_crop = get_rotate_crop_image(ori_img, tmp_box)
            img_crop_list.append(img_crop)

        rec_res = text_recognizer(img_crop_list)

    else:
        h, w = img.shape[:2]
        # 找出所有长度大于 w/2 的横线用于分割图片
        temp_list = []
        for row_line in row_lines:
            x1, y1, x2, y2 = row_line
            c_x, c_y = (x1 + x2) / 2, (y1 + y2) / 2

            line_length = dist((x1, y1), (x2, y2))
            if line_length > w / 2:
                temp_list.append(int(c_y))

        # 选择符合的横线横线
        temp_count = len(temp_list)
        ay1 = h / 4
        ay2 = h / 2
        ay3 = h * 3 / 4
        for m in range(temp_count):
            if temp_list[m] <= h / 4 < temp_list[m + 1]:
                ay1 = temp_list[m] * 2
            elif temp_list[m] <= h / 2 < temp_list[m + 1]:
                ay2 = temp_list[m] * 2
            elif temp_list[m] <= h * 3 / 4 < temp_list[m + 1]:
                ay3 = temp_list[m] * 2

        """ 图片放大为2*2，分割成4*1，沿横线进行切割"""
        resize_img = cv2.resize(img, (w * 2, h * 2))
        # 锐化
        kernel_sharpen = np.array([
            [0, -1, 0],
            [-1, 5, -1],
            [0, -1, 0]])
        resize_img = cv2.filter2D(resize_img, -1, kernel_sharpen)

        # 分割图片
        crop_img1 = resize_img[:ay1, :w * 2]
        crop_img2 = resize_img[ay1:ay2, :w * 2]
        crop_img3 = resize_img[ay2:ay3, :w * 2]
        crop_img4 = resize_img[ay3:, :w * 2]

        crop_img_list = [crop_img1, crop_img2, crop_img3, crop_img4]
        ay_list = [0, ay1, ay2, ay3]

        all_dt_boxes = []
        img_crop_list = []
        for i in range(len(crop_img_list)):
            ori_img = crop_img_list[i].copy()
            sub_det_boxes = text_detector(ori_img)

            if sub_det_boxes is not None:
                for bno in range(len(sub_det_boxes)):
                    tmp_box = copy.deepcopy(sub_det_boxes[bno])
                    img_crop = get_rotate_crop_image(ori_img, tmp_box)
                    img_crop_list.append(img_crop)

                for box in sub_det_boxes:
                    for k in range(len(box)):
                        bx, by = box[k]
                        box[k, 0] = int(bx / 2)
                        box[k, 1] = int((ay_list[i] + by) / 2)
                    all_dt_boxes.append(box)

        rec_res = text_recognizer(img_crop_list)

    # 返回识别的框和文字结果,一一对应
    return all_dt_boxes, rec_res


def get_roll_angle( lines ):
    """得到需要旋转的角度"""
    degree_list = []
    line_num = len(lines)
    for line in lines:
        x1, y1, x2, y2 = line
        if x1 != x2:
            k12 = (y2 - y1) / (x2 - x1)
            a12 = math.degrees(math.atan(k12))
        else:
            a12 = 90
        degree_list.append(a12)

    sort_list = sorted(degree_list)
    mid_degree = sort_list[line_num // 2]

    return mid_degree


def roll_image_horize( filepath, output_filepath, line_model ):
    """将图片进行旋转调正"""
    img = cv2.imread(filepath)
    input_size = (1024, 1024)
    prob = 0.2
    row = 100

    resize_img, fx, fy = resize(img, input_size)

    pred = line_model.predict(np.array([np.array(resize_img) / 255.0]))
    pred = pred[0]

    rows = pred[..., 0] > prob
    rows = rows.astype(int)

    # 根据模型得出的结果提取出识别出的横线
    row_lines = get_table_line(rows, axis=0, alph=row)

    # # 将提取出的线画在黑板上
    # tmp = np.zeros(input_size, dtype='uint8')
    # tmp = draw_lines(tmp, row_lines, color=255, line_width=2)
    # cv2.imwrite('temp_path/aa.png', tmp)

    # 计算需要旋转的角度
    roll_angle = get_roll_angle(row_lines)
    print("roll angle:", roll_angle)

    # 进行旋转
    roll_img = imutils.rotate_bound(img, -roll_angle)
    cv2.imwrite(output_filepath, roll_img)


def alter_lines( lines, axis=0 ):
    new_lines = []
    for line in lines:
        x1, y1, x2, y2 = line
        cx, cy = (x1 + x2) / 2, (y1 + y2) / 2

        if axis == 0:
            # print("cy:", cy)
            new_lines.append([int(x1), int(cy), int(x2) + 1, int(cy)])
        else:
            # print("cx:", cx)
            new_lines.append([int(cx), int(y1), int(cx), int(y2) + 1])

    return new_lines


def alter_close_lines( lines, alph=8, axis=0 ):
    line_num = len(lines)
    new_lines = []
    line_used = []
    mark_short = []  # 用于标记被合并的线，后面不再使用

    for i in range(line_num - 1):
        if i not in mark_short:
            x1, y1, x2, y2 = lines[i]

            for j in range(i + 1, line_num):
                if j not in mark_short:
                    x3, y3, x4, y4 = lines[j]

                    if axis == 0:
                        delta_y = abs(y3 - y1)

                        if delta_y < alph:
                            # print("两条横线间的距离y:", delta_y)
                            # 判断 x 是不是有重合
                            x_max = max(x1, x2, x3, x4)
                            x_min = min(x1, x2, x3, x4)

                            l1_length = abs(x2 - x1)
                            l2_length = abs(x4 - x3)

                            if (x_max - x_min) <= (l1_length + l2_length):
                                print("两条横线间的距离y:", delta_y)
                                # 优先合并后面的线
                                if l1_length + 2 >= l2_length:
                                    # 这部分耗时可能过多
                                    if [x_min, y1, x_max, y1] not in new_lines:
                                        new_lines.append([x_min, y1, x_max, y1])
                                        mark_short.append(j)
                                        line_used.append(i)
                                        line_used.append(j)
                                else:
                                    if [x_min, y3, x_max, y3] not in new_lines:
                                        new_lines.append([x_min, y3, x_max, y3])
                                        mark_short.append(i)
                                        line_used.append(i)
                                        line_used.append(j)
                                        break
                    else:
                        delta_x = abs(x3 - x1)

                        if delta_x < alph:
                            # print("两条竖线之间的距离x:", delta_x)
                            # 判断 y 是不是有重合
                            y_max = max(y1, y2, y3, y4)
                            y_min = min(y1, y2, y3, y4)

                            l1_length = abs(y2 - y1)
                            l2_length = abs(y4 - y3)

                            if (y_max - y_min) <= (l1_length + l2_length):
                                print("两条竖线之间的距离x:", delta_x)
                                if l1_length + 2 > l2_length:
                                    new_lines.append([x1, y_min, x1, y_max])
                                    mark_short.append(j)
                                    line_used.append(i)
                                    line_used.append(j)
                                else:
                                    new_lines.append([x3, y_min, x3, y_max])
                                    mark_short.append(i)
                                    line_used.append(i)
                                    line_used.append(j)
                                    break

    for i in range(line_num):
        if i not in line_used:
            new_lines.append(lines[i])

    return new_lines


def line_cross( rows, cols, alph=10 ):
    """竖线直线之间是否相交及相交的点往外突出一些"""
    for i in range(len(rows)):
        for j in range(len(cols)):
            # 取两条线的交点
            x1, y1, x2, y2 = rows[i]
            x3, y3, x4, y4 = cols[j]

            # 判断横线是否需要延长和竖线相交
            if (x1 >= x3 and x2 >= x3) or (x1 <= x3 and x2 <= x3):  # 横线在竖线一侧
                if y3 - alph < y1 < y4 + alph:
                    # 延长
                    if x3 <= x1 < x3 + alph:
                        rows[i] = [x3 - 1, y1, x2, y2]
                    elif x3 - alph < x2 <= x3:
                        rows[i] = [x1, y1, x3 + 1, y2]

            # 判断竖线是否需要延长和横线相交
            if (y3 >= y1 and y4 >= y1) or (y3 <= y1 and y4 <= y1):
                if x1 - alph < x3 < x2 + alph:
                    # 延长
                    if y1 <= y3 < y1 + alph:
                        cols[j] = [x3, y1 - 1, x4, y4]

                    elif y1 - alph < y4 <= y1:
                        cols[j] = [x3, y3, x4, y1 + 1]

    return rows, cols


def count_num( row, thresh=150, ratio=0.5 ):
    """
    用于判断该部分线段小于thresh部分是否超过一半
    :param row:
    :param thresh:
    :param ratio:
    :return:
    """
    count = 0
    row_length = len(row)
    for item in row:
        if item < thresh:
            count += 1

    if count / row_length > ratio:
        return True
    else:
        return False


def is_connect( left_line, right_line, row_y, word_boxes, image_path ):
    # 先找出两条竖线之间的word_box，然后再判断横线是否穿过某个box
    lx1, ly1, lx2, ly2 = left_line
    rx1, ry1, rx2, ry2 = right_line
    gray_image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

    # 找出box在 lx1到rx1之间的
    for box in word_boxes:
        x1, y1 = box[0]
        x2, y2 = box[1]
        x3, y3 = box[2]
        x4, y4 = box[3]
        cx = (x1 + x2 + x3 + x4) / 4

        if lx1 < cx < rx1:
            # 判断横线是否在box中
            min_y = min(y1, y2, y3, y4)
            max_y = max(y1, y2, y3, y4)
            if min_y + 1 < row_y < max_y - 1:
                # 穿过这个box，直接返回false表示线不延长
                return False

    # 没穿过box，判断三行的gray像素值，如果有一行黑色过多则表示存在线
    # 求lx1, rx1, row_y 的像素值
    for q in range(3):
        row = gray_image[row_y - 1 + q, lx1: rx1]
        pix_count = count_num(row)
        if pix_count:
            # 表示存在这条线需要连接起来
            return True

    return False


def is_connect2( up_line, down_line, col_x, word_boxes, image_path ):
    # 先找box
    ux1, uy1, ux2, uy2 = up_line
    dx1, dy1, dx2, dy2 = down_line
    gray_image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

    # 判断是否穿过box，是的话则返回False
    for box in word_boxes:
        x1, y1 = box[0]
        x2, y2 = box[1]
        x3, y3 = box[2]
        x4, y4 = box[3]
        cy = (y1 + y2 + y3 + y4) / 4

        if uy1 < cy < dy1:
            min_x = min(x1, x2, x3, x4)
            max_x = max(x1, x2, x3, x4)

            if min_x + 1 < col_x < max_x - 1:
                return False

    # 没有穿过box 判断黑色的比例是否需要延长
    for q in range(3):
        col = gray_image[uy1:dy1, col_x - 1 + q]
        pix_count = count_num(col)
        if pix_count:
            return True

    return False


def fix_up_lines( lines1, lines2, word_boxes, image_path, alph=5 ):
    """
    依次扫描每一条横线和竖线，判断其是否需要去除冒头的部分或延长冒头的部分。
    :param lines1:
    :param lines2:
    :param word_boxes:
    :param image_path:
    :param alph:
    :return:
    """
    new_row_lines = []
    new_col_lines = []
    for line1 in lines1:
        # 找到所有符合与其可能相交的线
        x1, y1, x2, y2 = line1

        left_index = []
        right_index = []
        cross_index = []

        for line2 in lines2:
            x3, y3, x4, y4 = line2

            if y3 - alph < y1 < y4 + alph:
                if x3 + 1 < x1:
                    left_index.append(line2)
                elif x3 - 1 > x2:
                    right_index.append(line2)
                else:
                    cross_index.append(line2)

        # 判断左侧是否需要延长或去除
        # 如果cross index 为空，则去除这条线
        if len(cross_index) != 0:
            cross_left_line = cross_index[0]
            cross_right_line = cross_index[-1]
            # 如果左边没有可能相交的线，则确定这条线最左边的端点为 (cross_left_line[0] - 1, y1)
            if len(left_index) == 0:
                # 最左边的端点为 (cross_left_line[0] - 1, y1)
                left_point = cross_left_line[0] - 1
            else:
                # 判断是否需要延长
                # 判断 corss_index[0]和line2之间的直线的中间点是否在文字框中，是则去除
                # 判断 左边点到 line2之间的线段 之间的阈值是否大于，是则连接，否则去除
                # 依次遍历左边的线，判断哪些需要延长
                left_length = len(left_index)
                left_point = cross_left_line[0] - 1
                for k in reversed(range(left_length)):
                    left_line = left_index[k]
                    # 判断这两条线在这个y坐标下是否需要连接
                    get_connect = is_connect(left_line, cross_left_line, y1, word_boxes, image_path)
                    if get_connect:
                        # 修改为左边的
                        left_point = left_line[0] - 1
                        print("延长左边一段！", line1)
                        continue
                    else:
                        break

            # 同理右侧
            if len(right_index) == 0:
                # 最右边的端点为 (cross_right_line[0] + 1, y1)
                right_point = cross_right_line[0] + 1
            else:
                right_length = len(right_index)
                right_point = cross_right_line[0] + 1
                for k in reversed(range(right_length)):
                    right_line = right_index[k]
                    get_connect = is_connect(cross_right_line, right_line, y1, word_boxes, image_path)
                    if get_connect:
                        right_point = right_line[0] + 1
                        print("延长右边一段：", line1)
                        continue
                    else:
                        break

            line1 = [left_point, y1, right_point, y2]
            new_row_lines.append(line1)

    # 同理处理竖线
    for line2 in lines2:
        x1, y1, x2, y2 = line2

        # 找到所有可能与其相交的横线
        up_index = []
        down_index = []
        cross_index = []
        for line1 in new_row_lines:
            x3, y3, x4, y4 = line1

            if x3 - alph < x1 < x4 + alph:
                if y3 + 1 < y1:
                    up_index.append(line1)
                elif y3 - 1 > y2:
                    down_index.append(line1)
                else:
                    cross_index.append(line1)

        # print("length:", len(up_index), len(down_index), len(cross_index))
        # print(cross_index)
        # 判断上面是否需要延长
        if len(cross_index) != 0:
            cross_up_line = cross_index[0]
            cross_down_line = cross_index[-1]

            # 如果上边没有可能相交的线，则确定这条竖线最上边的端点坐标为 (x1, cross_up_line[1] - 1)
            if len(up_index) == 0:
                up_point = cross_up_line[1] - 1
            else:
                # 判断是否需要延长
                up_length = len(up_index)
                up_point = cross_up_line[1] - 1
                for k in reversed(range(up_length)):
                    up_line = up_index[k]
                    # 判断上下两条线之间是否需要连接
                    get_connect = is_connect2(up_line, cross_up_line, x1, word_boxes, image_path)
                    if get_connect:
                        up_point = up_line[0] - 1
                        print("延长上边一段！", line2)
                        continue
                    else:
                        break

            # 同理下边一侧
            if len(down_index) == 0:
                down_point = cross_down_line[1] + 1
            else:
                down_length = len(down_index)
                down_point = cross_down_line[1] + 1
                for k in reversed(range(down_length)):
                    down_line = down_index[k]
                    get_connect = is_connect2(cross_down_line, down_line, x1, word_boxes, image_path)
                    if get_connect:
                        down_point = down_line[0] + 1
                        print("延长下边一段！", line2)
                        continue
                    else:
                        break

            line2 = [x1, up_point, x2, down_point]
            new_col_lines.append(line2)

    return new_row_lines, new_col_lines


def get_lines( filepath, line_model, input_size=(1024, 1024), prob=0.3, alph=30, row=30, col=30 ):
    """
    得到所有识别的表格线
    :param alph:
    :param filepath:
    :param line_model:
    :param input_size:
    :param prob:
    :param row:
    :param col:
    :return:
    """
    img = cv2.imread(filepath)
    h, w = img.shape[:2]
    resize_img, fx, fy = resize(img, input_size)

    pred = line_model.predict(np.array([np.array(resize_img) / 255.0]))
    pred = pred[0]

    rows = pred[..., 0] > prob
    cols = pred[..., 1] > prob
    rows = rows.astype(int)
    cols = cols.astype(int)

    # 根据模型得出的结果提取出识别出的横线和竖线
    row_lines = get_table_line(rows, axis=0, alph=row)
    col_lines = get_table_line(cols, axis=1, alph=col)
    # draw_img(input_size, row_lines + col_lines, 'temp_path/aa.png')

    # 去除识别出来的线中不平行的线
    # 平行线之间的误差：1.5°
    delta_angle = 1.5
    row_lines = not_par_line(row_lines, delta_angle)
    col_lines = not_par_line(col_lines, delta_angle)
    # draw_img(input_size, row_lines + col_lines, 'temp_path/bb.png')

    # 转换成原尺寸
    if len(row_lines) > 0:
        row_lines = np.array(row_lines)
        row_lines[:, [0, 2]] = row_lines[:, [0, 2]] / fx
        row_lines[:, [1, 3]] = row_lines[:, [1, 3]] / fy
        row_lines = row_lines.tolist()

    if len(col_lines) > 0:
        col_lines = np.array(col_lines)
        col_lines[:, [0, 2]] = col_lines[:, [0, 2]] / fx
        col_lines[:, [1, 3]] = col_lines[:, [1, 3]] / fy
        col_lines = col_lines.tolist()

    # 对线进行从左到右从上到下排序
    row_lines = sort_line(row_lines)
    col_lines = sort_line(col_lines, axis=1)

    # 断续的横线或竖线进行连接
    row_lines = find_unclear_lines(row_lines, alph)
    col_lines = find_unclear_lines(col_lines, alph)

    # 对线进行从左到右从上到下排序
    # row_lines = sort_line(row_lines)
    # col_lines = sort_line(col_lines, axis=1)
    # draw_img((h, w), row_lines + col_lines, 'temp_path/cc.png')

    return row_lines, col_lines
